package com.xudow.app.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.dynamicstate_old.module.guide.ClazzActivity;
import com.xudow.app.newui.home.HomeActivity;
import com.xudow.app.ui.task.MobilePhoneBindTask;
import com.xudow.app.ui.task.RegisterTask;
import com.xudow.app.ui.task.VcodeTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 绑定手机Activity
 *
 * @author lukecheng
 */
public class MobilePhoneBindActivity extends BaseActivity {

    private EditText cellphoneEditText;
    private EditText vcodeEditText;
    private LinearLayout vcodeSendBtn;
    private TextView vcodeText;

    /**
     * 验证码重新获取倒计时
     */
    private VcodeTask vcodeTask;
    private int vcodeCountDown = 60;
    private Timer vcodeTimer;
    private TimerTask vcodeTimerTask;

    private MobilePhoneBindTask mobilephoneBindTask;

    private void initVcodeTimerTask() {
        vcodeCountDown = 60;

        vcodeTimerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (vcodeCountDown <= 0) {
                            vcodeSendBtn.setClickable(true);
                            vcodeText.setText(getString(R.string.common_vcode_again));
                            vcodeTimerTask.cancel();
                        } else {
                            String countdownTxt = getString(R.string.common_vcode_countdown, vcodeCountDown);
                            vcodeText.setText(countdownTxt);
                        }

                        vcodeCountDown--;
                    }
                });
            }
        };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile_phone_bind);

        cellphoneEditText = (EditText) findViewById(R.id.cellphone);
        vcodeEditText = (EditText) findViewById(R.id.vcode);

        vcodeSendBtn = (LinearLayout) findViewById(R.id.vcode_send_btn);
        vcodeText = (TextView) findViewById(R.id.vcode_btn_txt);
    }

//    public void onBackBtnClick(View view) {
//        finish();
//    }

    /**
     * 保存点击事件
     *
     * @param view
     */
    public void onSaveClick(View view) {
        String cellphone = cellphoneEditText.getText().toString().trim();
        if (StringUtils.isEmpty(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_required));
            return;
        }

        if (!StringUtils.isMobile(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_format_err));
            return;
        }

        String vcode = vcodeEditText.getText().toString().trim();
        if (StringUtils.isEmpty(vcode)) {
            vcodeEditText.setError(getString(R.string.vcode_required));
            return;
        }

        HashMap<String, String> params = Maps.newHashMap();
        params.put("mobilephone", cellphone);
        params.put("v_code", vcode);

        showLodingDialog(getString(R.string.processing));

        mobilephoneBindTask = new MobilePhoneBindTask(this, phoneBindHandler);
        addTask(mobilephoneBindTask);
        mobilephoneBindTask.execute(params);
    }

    /**
     * 获取验证码Handler
     */
    private Handler vcodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (VcodeTask.SUCCESS == msg.what) {
                String vcodeSuccess = getString(R.string.common_vcode_success);
                Toast.makeText(MobilePhoneBindActivity.this, vcodeSuccess, Toast.LENGTH_SHORT).show();

                vcodeSendBtn.setClickable(false);

                initVcodeTimerTask();
                vcodeTimer = new Timer();
                vcodeTimer.scheduleAtFixedRate(vcodeTimerTask, 1000, 1000);
            } else {
                String errVcode = getString(R.string.common_vcode_err);
                Toast.makeText(MobilePhoneBindActivity.this, errVcode, Toast.LENGTH_LONG).show();
            }
        }
    };

    /**
     * 获取验证码
     *
     * @param view
     */
    public void onGetVcodeClick(View view) {
        String cellphone = cellphoneEditText.getText().toString().trim();
        if (StringUtils.isEmpty(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_required));
            return;
        }

        if (!StringUtils.isMobile(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_format_err));
            return;
        }

        showLodingDialog(getString(R.string.common_vocde_send));

        HashMap<String, String> vcodeParams = Maps.newHashMap();
        vcodeParams.put("phone", cellphone);
        vcodeParams.put("type", Config.VOCDE_TYPE_REGISTER);

        vcodeTask = new VcodeTask(this, vcodeHandler);
        vcodeTask.execute(vcodeParams);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (KeyEvent.KEYCODE_BACK == keyCode) {
//            if (null != vcodeTask && !vcodeTask.isCancelled()) {
//                vcodeTask.cancel(true);
//                vcodeTask = null;
//            }
//
//            if (null != mobilephoneBindTask && !mobilephoneBindTask.isCancelled()) {
//                mobilephoneBindTask.cancel(true);
//                mobilephoneBindTask = null;
//            }
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }
    //设置返回键动作（阻塞返回键)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO 自动生成的方法存根
        if(keyCode==KeyEvent.KEYCODE_BACK) {

            return false;

        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 手机绑定Handler
     */
    private Handler phoneBindHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            switch (msg.what) {
                case MobilePhoneBindTask.SUCCESS:
                    success();
                    break;
                case MobilePhoneBindTask.ERROR:
                    error(msg.getData());
                    break;
            }
        }
    };

    private void success() {
        String successStr = getString(R.string.mobile_phone_bind_success);
        Toast.makeText(this, successStr, Toast.LENGTH_LONG).show();
        if (!application.isHasAttentionType()) {
            Log.i("MobilePhoneBindActivity","successsuccess");
            Intent intent = new Intent(MobilePhoneBindActivity.this, ClazzActivity.class);
            intent.putExtra("isLogin", true);
            startActivity(intent);
        } else{
            startActivity(new Intent(this, HomeActivity.class));
        }

        finish();
    }

    private void error(Bundle data) {
        String message = data.getString("errMessage");

        if (StringUtils.isEmpty(message)) {
            message = getString(R.string.mobile_phone_bind_fail);
        }

        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

}
